package com.LeeCode;

/**
 * 链表最大孪生和
 */

public class Code2130 {

    public static void main(String[] args) {
        int[] arr = {5, 4, 2, 1};
        ListNode head = Utils.arrayToListNode(arr);
        System.out.println(new Code2130().pairSum(head));
    }

    public int pairSum(ListNode head) {
        ListNode slow = head, fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode head1 = reverse(slow);
        int ans = 0;
        while (head1 != null) {
            ans = Math.max(ans, head1.val + head.val);
            head1 = head1.next;
            head = head.next;
        }
        return ans;
    }

    private ListNode reverse(ListNode head) {
        ListNode prev = null, cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}
